<template>
  <el-scrollbar @scroll="showMenu = false">
    <ul class="messages-ul">
      <li
        v-for="([key, { LatestMessInfo }], index) in chatList"
        :key="LatestMessInfo.messageId"
        :class="{ 'is-actived': currentId === key }"
        @click="trueChatRecord(key)"
        @contextmenu.prevent="openMenu(key, $event)"
      >
        <div
          :class="{
            'messages-item': true,
            'messages-item__nolast': index !== chatList.size - 1,
            clearfix: true,
          }"
        >
          <div class="messages-item__left">
            <div class="friends-avatar">
              <img :src="LatestMessInfo.avatar" alt="" />
            </div>
          </div>
          <div class="messages-item__right">
            <span class="friends-name messages-name">{{ LatestMessInfo.remark }}</span>
            <template v-if="LatestMessInfo.time"
              ><span class="messages-newMess__time" v-time="LatestMessInfo.time"></span
            ></template>
            <div class="messages-messBottom">
              <template v-if="LatestMessInfo.latestMess"
                ><span
                  class="messages-newMess"
                  v-if="LatestMessInfo.type === 'text'"
                  v-filtlatemess="
                    replaceEmotion(LatestMessInfo.latestMess, 'chat-message__emotion')
                  "
                ></span
                ><span
                  class="messages-newMess"
                  v-else-if="LatestMessInfo.type === 'voice'"
                  >[语音]</span
                ></template
              >
              <span v-if="LatestMessInfo.unReadMessCou" class="unReadMessLen">{{
                LatestMessInfo.unReadMessCou > 99 ? "99+" : LatestMessInfo.unReadMessCou
              }}</span>
            </div>
          </div>
        </div>
      </li>
    </ul>
  </el-scrollbar>
  <opea-menu ref="menu" v-model="showMenu" :user-id="operateId"></opea-menu>
</template>

<script lang="ts" setup>
import { ref, onBeforeMount, onMounted, onBeforeUnmount, nextTick, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import vTime from "@/directives/time";
import vFiltlatemess from "@/directives/filterLatestMess";
import Trigger from "@/plugins/rigClickOpMen";
import opeaMenu from "./menu.vue";
import { useMessagePinia } from "@/pinia/messages";
import { storeToRefs } from "pinia";
import { replaceEmotion } from "@/directives/filterText";

const router = useRouter();
const route = useRoute();
const { chatList } = storeToRefs(useMessagePinia());

/**
 * 当前页面所显示的聊天记录的名称
 */
let currentId = ref<string>("");
/**
 * 用户与某位好友的具体聊天记录
 * @param userId - 用户的账号
 */
const trueChatRecord: (userId: string) => void = (userId: string) =>
  router.push({ name: "chatRecord", query: { userId } });

watch(
  () => route.query.userId as string,
  (newUserId: string) => (currentId.value = newUserId)
);

onBeforeMount(() => {
  if (route.query.userId) currentId.value = route.query.userId as string;
});

let trigger = ref<Trigger>();
onMounted(() =>
  setTimeout(() => {
    const ele: HTMLElement = document.getElementById("middle-main") as HTMLElement;
    trigger.value = new Trigger(ele);
    trigger.value.resize();
  })
);
onBeforeUnmount(() => {
  trigger.value?.removeResize();
});

/**
 * 是否需要打开鼠标右击后出现的菜单
 */
const showMenu = ref<boolean>(false);
/**
 * 给鼠标右击出现的菜单元素组件一个ref属性，便于通过$refs访问
 */
const menu = ref<typeof opeaMenu>();
/**
 * 当前用户选择的聊天会话对象的userId
 */
const operateId = ref<string>("");
/**
 * 鼠标右键打开操作菜单
 */
const openMenu: (key: string, $event: MouseEvent) => void = (
  key: string,
  $event: MouseEvent
): void => {
  const data = chatList.value.get(key);
  if (!data?.isNodisplayLoading && !data?.isToppingLoading) {
    showMenu.value = true;
    operateId.value = key;
    nextTick(() =>
      trigger.value?.computedDirection(menu.value?.$refs.menu as HTMLDListElement, $event)
    );
  }
};
</script>

<style lang="scss" scoepd>
.messages {
  &-ul {
    li {
      cursor: pointer;
      padding: 0 8px;
      transition: background-color 0.25s;

      &:hover,
      &.is-actived {
        background-color: rgba(193, 191, 191, 0.114);
      }
    }
  }

  &-item {
    display: block;
    color: #333;
    padding: 18px 0 16px 8%;
    box-sizing: border-box;

    &__nolast {
      border-bottom: 1px solid $bottomBorCor;
    }

    @mixin leRi($width) {
      float: left;
      width: $width;
    }

    &__left {
      @include leRi(20%);

      img {
        @include setWidHei(100%, 100%);
        border-radius: 50%;
        object-fit: cover;
      }
    }

    &__right {
      @include leRi(78%);
      margin-left: 2%;

      .unReadMessLen {
        display: inline-block;
        @include promptMessCount(14px, 25px, 25px, 0.8);
        vertical-align: 3px;
        margin-left: 5px;
      }
    }
  }

  @mixin omit($size) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-size: $size;
  }

  &-name {
    @include omit(14px);
    display: inline-block;
  }

  &-messBottom {
    margin: 4px 0 0;
    height: 25px;
    box-sizing: border-box;
  }

  &-newMess {
    display: inline-block;
    width: 79%;
    @include omit(13px);
    color: $dimFontCor;

    &__time {
      display: inline-block;
      width: 66px;
      text-align: right;
      font-size: 13px;
      vertical-align: top;
      color: $dimFontCor;
    }
  }
}
</style>
